declare @KEHOACH Table(
	[ID] int,
	DON_VI_ID int,
	[CHI_TIEU_ID] int
)
declare @DONVI_CHITIEU Table(
	DON_VI_ID int,
	[CHI_TIEU_ID] int
)

declare @R3 Table(
	ID int,
	DON_VI_ID int,
	[CHI_TIEU_ID] int,
	DonViId int,
	ChiTieuId int
)

	insert into @KEHOACH
	SELECT ID, DON_VI_ID, [CHI_TIEU_ID]
	FROM [NV].[KEHOACH]
	WHERE [NAM_KE_HOACH_ID] = 2016 and STATUS_ID=10 and 
	[CHI_TIEU_ID] in (select [CHI_TIEU_ID] from [NV].[DONVI_CHITIEU] 
	where [NAM_KE_HOACH_ID] = 2016 and [DON_VI_ID]  = 46 and FLAG = 1)
	order by CHI_TIEU_ID

insert into @DONVI_CHITIEU
SELECT DON_VI_ID, [CHI_TIEU_ID]
	FROM [NV].[DONVI_CHITIEU]
	where [NAM_KE_HOACH_ID]  = 2016 and [FLAG] = 0 and
	[DON_VI_ID] in (Select [DON_VI_ID] from [DM].[DONVI] 
		where [CO_QUYEN_GIAM_SAT] = 0 or [CO_QUYEN_GIAM_SAT] = 2)
	and  [CHI_TIEU_ID] in (select [CHI_TIEU_ID] from [NV].[DONVI_CHITIEU]
	 where [NAM_KE_HOACH_ID] = 2016 and [DON_VI_ID]  = 46 and FLAG = 1)
		order by CHI_TIEU_ID

insert into @R3 
select t.ID, t.DON_VI_ID, t.CHI_TIEU_ID, 
	d.DON_VI_ID as DonViId, d.CHI_TIEU_ID as ChiTieuId
 from @KEHOACH t left join @DONVI_CHITIEU d
on t.DON_VI_ID = d.DON_VI_ID and 
t.CHI_TIEU_ID = d.CHI_TIEU_ID

select * from @R3 
where DonViId is null and ChiTieuId is null

--select * from [NV].[KEHOACH]
--where ID in (SElect ID from @R3)

--DELETE FROM [NV].[KEHOACH]
--where ID in (SElect ID from @R3
--			where DonViId is null and ChiTieuId is null
--)

